package withdraw

import (
	"context"
	"encoding/json"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/user"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/dataview"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/merchant"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/settingtoc"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	settingrpc "gitee.com/liuxuezhan/ar-platform/rpc-client/setting/rpc"
	"github.com/bytedance/sonic"
	"github.com/spf13/cast"
	"github.com/zeromicro/go-zero/core/logc"
)

var MerchantId int64

type WithdrawService struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWithdrawService(ctx context.Context, svcCtx *svc.ServiceContext) *WithdrawService {
	return &WithdrawService{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (w *WithdrawService) VerifyMarkConsume(userId int64) error {
	resp, err := w.svcCtx.SettingRpc.DataView(w.ctx, &settingtoc.DataViewReq{
		MerchantId: 1,
		ModelType:  1,
		Type:       10010,
	})
	if err != nil {
		return err
	}
	var m map[string]int
	if err = sonic.UnmarshalString(resp.Data.List[0].Value, &m); err != nil {
		return err
	}

	t, ok := m["status"]
	if ok && t == 1 {
		userWallet, err := user.NewWalletModel(w.ctx, w.svcCtx.Db).FindUserWallet(userId)
		if err != nil {
			return err
		}
		if userWallet.ValidConsume < userWallet.ValidMark {
			return xerrors.ErrConsumeMustGreaterEqualMark
		}
	}

	return nil
}
func IsOpen(svcCtx *svc.ServiceContext, ctx context.Context, in int64, value string) int64 {

	ModelType := in / 10000
	if _, ok := common.All[int64(ModelType)]; !ok {
		return 0
	}

	u, err := svcCtx.SettingRpc.DataView(ctx, &dataview.DataViewReq{
		ModelType:  rpc.ModelType(ModelType),
		MerchantId: MerchantIdGet(svcCtx.SettingRpc, ctx),
		Type:       in,
	})

	if err != nil {
		logc.Error(ctx, "DataViewList err:", err)
		return 0
	}

	if u.Code != int64(xerrors.SettingRpcSuccessful.Code()) {
		return 0
	}
	for _, v := range u.Data.List {
		vs := map[string]interface{}{}
		_ = json.Unmarshal([]byte(v.Value), &vs)
		return cast.ToInt64(vs[value])
	}
	return 0
}
func AddNotificationMessageToCReq(svcCtx *svc.ServiceContext, ctx context.Context, UserId int64, MessageType int64) error {
	d := &settingrpc.AddNotificationMessageToCReq{
		MessageType: MessageType,
		UserId:      UserId,
		Language:    "ar",
		Value:       []string{},
		MerchantId:  MerchantIdGet(svcCtx.SettingRpc, ctx),
	}
	_, err := svcCtx.SettingRpc.AddNotificationMessage(ctx, d)
	return err
}
func MerchantIdGet(svcCtx settingtoc.SettingToC, ctx context.Context) int64 {
	if MerchantId == 0 {
		d, err := svcCtx.GetMerchantId(ctx, &merchant.MerchantToCReq{})
		if err != nil {
			return MerchantId
		}
		MerchantId = d.Data.GetId()
	}
	return MerchantId
}
